//
//  MAHomeViewController.m
//  meiang_edu
//
//  Created by Liubi_Chaos_G on 2018/7/30.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAHomeViewController.h"

#import "MAHomeChildViewController.h"
#import "ChaosLabel.h"
#import "MATabBarViewController.h"
#import "MALoginViewController.h"
#import <zhPopupController.h>
#import "MAPopView.h"
#import "MABabyModel.h"
#import "MAPopViewCell.h"
#import "MAUserInfoViewController.h"

#define ChaosLabelW 70.0

@interface MAHomeViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIScrollView *titleScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
/** searchTF */
@property(nonatomic,strong) UITextField *searchTF;
/** leftIcon */
@property(nonatomic,strong) UIImageView *leftIcon;

/** labels 导航标签 */
@property(nonatomic,strong) NSMutableArray *labels;

/** babyModels */
@property(nonatomic,strong) NSMutableArray *babyModels;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleScrollTopCons;

/** followStatusText */
@property(nonatomic,copy) NSString *followStatusText;


@end

@implementation MAHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupBasic];
    
    [self sendRequestForLabels];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessed) name:kMALoginSuccessedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLougout) name:@"user_logout" object:nil];
    self.followStatusText = @"展开关注列表";
}

- (void)userLougout
{
    // 跳转页面
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = [[MATabBarViewController alloc] init];
    window.rootViewController = vc;
}

- (void)loginSuccessed {
    
    // 跳转页面
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = [[MATabBarViewController alloc] init];
    window.rootViewController = vc;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenTabbar:NO];
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    if (userinfo.token) {
        NSString *imgUrl = userinfo.token ? [NSString stringWithFormat:@"%@%@",IMG_OSS,userinfo.ps_id] : @"";
        [self.leftIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"homepage_navigationbar_picture"]];
    }
}
- (void)setupBasic {
    self.title = @"首页";
    
    if (IS_IPHONE_X) {
        self.titleScrollTopCons.constant = 84;
    } else {
        self.titleScrollTopCons.constant = 64;
    }
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    NSString *imgUrl = userinfo.token ? [NSString stringWithFormat:@"%@%@",IMG_OSS,userinfo.ps_id] : @"";
    [self.leftIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"homepage_navigationbar_picture"]];
    
    [self.leftIcon addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftBtnDidClick)]];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 7.0, 30.0, 30.0)];
    [leftView addSubview:self.leftIcon];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 0.0, 35.0, 35.0)];
    
    [rightBtn addTarget:self action:@selector(rightBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"dropdownbutton_logo"] forState:UIControlStateNormal];
    
    //修改方法
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 35.0, 35.0)];
    [view addSubview:rightBtn];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    
    
    self.navigationItem.rightBarButtonItem = rightItem;
//    [UIBarButtonItem itemWithTarget:self action:@selector(rightBtnDidClick) image:@"dropdownbutton_logo" highImage:@"dropdownbutton_logo"];
    
    UITextField *searchTF = [[UITextField alloc] init];
    searchTF.width = SCREEN_WIDTH;
    searchTF.height = 30;
    searchTF.borderStyle = UITextBorderStyleRoundedRect;
    searchTF.font = Font(FONT_SIZE_14);
    searchTF.placeholder = @"搜您想搜的";
    self.searchTF = searchTF;
    self.navigationItem.titleView = searchTF;
}

- (void)leftBtnDidClick {
    DLog(@"");
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    if (!userinfo.token) {
        // 登录
        MALoginViewController *vc = [[MALoginViewController alloc] init];
        [self presentViewController:vc animated:YES completion:^{
            
        }];
        
    } else { // 个人中心页面
        MAUserInfoViewController *vc = [[MAUserInfoViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)rightBtnDidClick {
    DLog(@"");
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        
        request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=user_child&status=-1",BASE_LISTENTITY_LIST,userinfo.ID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.babyModels = [MABabyModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            
            MAPopView *popView = [MAPopView popView];
            popView.layer.cornerRadius = 10;
            popView.myTableView.delegate = self;
            popView.myTableView.dataSource = self;
            popView.layer.masksToBounds = YES;
            popView.height = 40 + self.babyModels.count * 40;
            self.zh_popupController = [[zhPopupController alloc] init];
            self.zh_popupController.dismissOnMaskTouched = YES;
            self.zh_popupController.dismissOppositeDirection = YES;
            self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
            [self.zh_popupController presentContentView:popView duration:0.35 springAnimated:YES];
            [popView.myTableView reloadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1 + self.babyModels.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    MAPopViewCell *popcell = [MAPopViewCell cellWithTableView:tableView];
//    if (row == 0) {
//        popcell.nameLabel.text = @"扫一扫关注";
//    } else if (row == 1) {
//        popcell.nameLabel.text = @"成长记录";
//    } else
    if (row == 0) {
        popcell.nameLabel.text = self.followStatusText;
    } else {
        MABabyModel *model = self.babyModels[row - 1];
        popcell.nameLabel.text = [NSString stringWithFormat:@"切换为 %@ 消息",model.cname];
    }
    return popcell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DLog(@"");
    NSInteger row = indexPath.row;
    MAPopViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (row == 0) { // 展开/关闭关注列表
        if ([cell.nameLabel.text isEqualToString:@"展开关注列表"]) {
            cell.nameLabel.text = @"隐藏关注列表";
            self.followStatusText = @"隐藏关注列表";
            [[NSNotificationCenter defaultCenter] postNotificationName:kMAExtendJiGouFollowListNotification object:nil];
        } else {
            cell.nameLabel.text = @"展开关注列表";
            self.followStatusText = @"展开关注列表";
            [[NSNotificationCenter defaultCenter] postNotificationName:kMAHideJiGouFollowListNotification object:nil];
        }
    }
    [self.zh_popupController dismiss];
}

- (void)sendRequestForLabels {
    [self.labels removeAllObjects];
    [self.labels addObject:@"资讯"];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    if (!userinfo.token) {
        // 添加子控制器
        [self setupChildVC];
        
        // 添加标题
        [self setupTitle];
        
        // 默认显示第0个子控制器
        [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
        return;
    }
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = HOME_LABEL_LIST;
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeCache;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            [self.labels removeAllObjects];
            for (NSDictionary *dic in dataDict[@"value"]) {
                [self.labels addObject:dic[@"labels"]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                // 添加子控制器
                [self setupChildVC];
                
                // 添加标题
                [self setupTitle];
                
                // 默认显示第0个子控制器
                [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
            });
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

/**
 * setupChildVc
 */
- (void)setupChildVC
{
    for (NSString *title in self.labels) {
        
        MAHomeChildViewController *vc5 = [[MAHomeChildViewController alloc] init];
        vc5.title = title;
        [self addChildViewController:vc5];
    }
}

/**
 * 添加标题
 */
- (void)setupTitle
{
    // 定义临时变量
    CGFloat labelW = ChaosLabelW;
    CGFloat labelY = 0;
    CGFloat labelH = self.titleScrollView.frame.size.height;
    NSInteger count = self.childViewControllers.count;
    // 添加label
    for (NSInteger i = 0; i<count; i++) {
        ChaosLabel *label = [[ChaosLabel alloc] init];
        label.text = [self.childViewControllers[i] title];
        CGFloat labelX = i * labelW;
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
        label.tag = i;
        
        [self.titleScrollView addSubview:label];
        
        if (i == 0) { // 最前面的label
            label.scale = 1.0;
        }
    }
    
    // 设置contentSize
    self.titleScrollView.contentSize = CGSizeMake(count * labelW, 0);
    self.contentScrollView.contentSize = CGSizeMake(count * [UIScreen mainScreen].bounds.size.width, 0);
}

/**
 * 监听顶部label点击
 */
- (void)labelClick:(UITapGestureRecognizer *)tap
{
    // 取出被点击label的索引
    NSInteger index = tap.view.tag;
    
    // 让底部的内容scrollView滚动到对应位置
    CGPoint offset = self.contentScrollView.contentOffset;
    offset.x = index * self.contentScrollView.frame.size.width;
    [self.contentScrollView setContentOffset:offset animated:YES];
    
}

#pragma mark - <UIScrollViewDelegate>
/**
 * scrollView结束了滚动动画以后就会调用这个方法（比如- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法执行的动画完毕后）
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (!self.labels.count) {
        return;
    }
    // 一些临时变量
    CGFloat width = scrollView.frame.size.width;
    CGFloat height = scrollView.frame.size.height;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    // 当前位置需要显示的控制器的索引
    NSInteger index = offsetX / width;
    
    // 让对应的顶部标题居中显示
    ChaosLabel *label = self.titleScrollView.subviews[index];
    CGPoint titleOffset = self.titleScrollView.contentOffset;
    titleOffset.x = label.center.x - width * 0.5;
    // 左边超出处理
    if (titleOffset.x < 0) titleOffset.x = 0;
    // 右边超出处理
    CGFloat maxTitleOffsetX = self.titleScrollView.contentSize.width - width;
    if (titleOffset.x > maxTitleOffsetX) titleOffset.x = maxTitleOffsetX;
    if (self.labels.count > 3) {
        [self.titleScrollView setContentOffset:titleOffset animated:YES];
    }
    // 让其他label回到最初的状态
    for (ChaosLabel *otherLabel in self.titleScrollView.subviews) {
        if (otherLabel != label) {
            otherLabel.scale = 0.0;
        }
    }
    
    // 取出需要显示的控制器
    UIViewController *willShowVc = self.childViewControllers[index];
    
    // 如果当前位置的位置已经显示过了，就直接返回
    if ([willShowVc isViewLoaded]) return;
    
    // 添加控制器的view到contentScrollView中;
    willShowVc.view.frame = CGRectMake(offsetX, 0, width, height);
    [scrollView addSubview:willShowVc.view];
}

/**
 * 手指松开scrollView后，scrollView停止减速完毕就会调用这个
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (!self.labels.count) {
        return;
    }
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

/**
 * 只要scrollView在滚动，就会调用
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.labels.count < 3) {
        return;
    }
    // 一些临时变量
    CGFloat width = scrollView.frame.size.width;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    // 当前位置需要显示的控制器的索引
    CGFloat index = offsetX / width;
    
    CGFloat scale = scrollView.contentOffset.x / scrollView.frame.size.width;
    if (scale < 0 || scale > self.titleScrollView.subviews.count - 1) return;
    
    // 获得需要操作的左边label
    NSInteger leftIndex = scale;
    ChaosLabel *leftLabel = self.titleScrollView.subviews[leftIndex];
    
    // 获得需要操作的右边label
    NSInteger rightIndex = leftIndex + 1;
    ChaosLabel *rightLabel = (rightIndex == self.titleScrollView.subviews.count) ? nil : self.titleScrollView.subviews[rightIndex];
    
    // 右边比例
    CGFloat rightScale = scale - leftIndex;
    // 左边比例
    CGFloat leftScale = 1 - rightScale;
    
    // 设置label的比例
    leftLabel.scale = leftScale;
    rightLabel.scale = rightScale;
}

#pragma mark - getter & setter
- (UIImageView *)leftIcon {
    if (_leftIcon == nil) {
        UIImageView *leftBtn = [[UIImageView alloc] init];
        leftBtn.width = 30;
        leftBtn.height = 30;
        leftBtn.x = -3;
        leftBtn.y = 0;
        leftBtn.layer.cornerRadius = 15;
        leftBtn.layer.masksToBounds = YES;
        leftBtn.userInteractionEnabled = YES;
        _leftIcon = leftBtn;
    }
    return _leftIcon;
}

- (NSMutableArray *)labels {
    if (_labels == nil) {
        _labels = [NSMutableArray array];
    }
    return _labels;
}

- (NSMutableArray *)babyModels {
    if (_babyModels == nil) {
        _babyModels = [NSMutableArray array];
    }
    return _babyModels;
}

@end
